<html>
<head>
<title>锁具移交</title>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>
<link rel="shortcut icon" href="resources/images/lock.png" type="image/x-icon">
<link rel="stylesheet" href="resources/css/stylemain.css">
<link rel="stylesheet" href="resources/layui/css/layui.css">

<link rel="stylesheet" href="resources/font-awesome-4.7.0/css/font-awesome.min.css" media="all">
<script src="resources/layui/layui.all.js"></script>
<script type="text/javascript" src="resources/js/jquery.js"></script>
<script type="text/javascript" src="resources/js/base64.js"></script>
<script type="text/javascript" src="resources/js/getMessage.js"></script>
</head>
<body>
	<div class="container">
		<img id="imgPreview" height="200" width="150" />		
	</div>
	<form class="layui-form" action="">
		<input id="fingerflag_1" type="radio" name="fingerflag" value="1" title="指纹一" checked="">
		<input id="fingerflag_2" type="radio" name="fingerflag" value="2" title="指纹二">
		<input id="fingerflag_3" type="radio" name="fingerflag" value="3" title="指纹三">
		<input type="text" id="username" lay-verify="required"  placeholder="用户名" class="layui-input">
		<input type="button" value="采集指纹" onclick="FPIGetFeature(1);" />
		<input type="button" value="验证指纹" onclick="FPIGetFeature(2);" />
		<input type="button" value="指纹识别" onclick="getFinger();" />
	</form>
<script type="text/javascript">
var layer = layui.layer;
var form = layui.form;
var webSocket = {};
var fingeropt = 0;
layui.use([], function(){
	debugger;	
	//CreateWebSocket();
	form.render();
});

//创建websockt
function CreateWebSocket() {
	webSocket = new WebSocket("ws://localhost:8082");
	webSocket.onopen = WebSokectOnOpen;
	webSocket.onmessage = WebSocketOnMessage;
	webSocket.onclose = WebSocketOnClose;
};

//建立连接事件
function WebSokectOnOpen() {
	//alert("已经打开连接！");
	webSocket.send("connection Success!");
};

//监听消息（cmd$&ack$&data)
function WebSocketOnMessage(event) {
	//监听来自服务端的数据
	if(event.data == "") {
		return;
	}
	// 拆分消息内容
	var messageArray = event.data.split("$&");
	if(messageArray.length < 3) {
		// 不够3个元素，表示异常了
		return;
	}
	
	if (messageArray[0] == '102') {
		console.log(event.data);
	}
	
	// 显示提示信息（成功/失败）
	if (messageArray[0] == '900'){
		TranslateMessage(9, messageArray[1]);
	}
	else{
		var message = TranslateMessage(1, messageArray[1]);
		if(message != ""){
			if(messageArray[1] == "1102"){
				layer.msg(message,{
					  icon: 1,
					  time: 14000 //2秒关闭（如果不配置，默认是3秒）
				});
			}else{
				if(messageArray[1] > 0){
					layer.msg(message,{
						  icon: 1,
						  time: 2000 //2秒关闭（如果不配置，默认是3秒）
					});
				}else {
					layer.msg(message,{
						  icon: 2,
						  time: 2000 //2秒关闭（如果不配置，默认是3秒）
					});
				}
				
			}
			
		}		
	}
	
	// 显示模板/特征
	if(messageArray[1] == "1201") // 取得模板数据
	{
		//$("#registerData").text(messageArray[2]);
		FPIFpGetImg('0');
	}

	if(messageArray[1] == "1202") // 取得特征数据
	{
		//$("#gatherData").text(messageArray[2]);
		FPIFpGetImg('1');
	}
	
	// 图像数据
	if (messageArray[0] == '103'){
		if (messageArray[1] == '1000')
		{
			$("#imgPreview").attr("src", "data:image/bmp;base64," + messageArray[2]);
			//上传指纹图像
			uploadfinger(messageArray[2]);
		}				
	}
};

function WebSocketOnClose() {
	//监听来自客户端的数据
	alert('和服务器断开连接');
};

//cmd:指令
//100-注册模板
//101-采集指纹
//102-指纹对比
//parameters:参数(多个参数用“$&”隔开)
function WebSocketSendMessage(cmd, parameters) {
	//发送到服务器
	if(cmd == null || cmd == "") {
		alert('指令未定义或不能为null!');
		return;
	}
	if(parameters == "" || parameters == undefined) {
		webSocket.send(cmd);
		return;
	} else {
		webSocket.send(cmd + '$&' + parameters);
	}
};

//采集指纹
function FPIGetFeature(opt) {
	var port = 0;
	var time = 15;
	fingeropt = opt;
	WebSocketSendMessage('101', port + '$&' + time);
}

function FPIFpGetImg(imgIndex){
	WebSocketSendMessage('103', imgIndex);
}

function mxGetMb(port, call_back_fun){
	  var ws = new WebSocket("ws://localhost:8001/finger");
	  ws.onopen = function(evt) {
	  	var command = "FPGetMb|"+port+"|"+"";
		  ws.send(command);
		}

	  ws.onmessage = function(evt) {
		  ws.close();
		  var resp = eval('('+evt.data+')');
	      call_back_fun(resp.result, resp.data);
	  };

	  ws.onclose = function(evt) {
	  };
}

function getFinger(){
	fingeropt = 3;
	mxGetMb(0, function(result, data)
			{
			 
			   if(result!=0)
			   {  
				   layer.msg("指纹采集失败:" + result, {icon: 2,time: 2000});
				   return;
			   }
			   else
			   {
				   uploadfinger(data);
			   }
			});
}

function uploadfinger(fingerbase){
	var datastring = '{"username":"'+$('#username').val().replace(/\s+/g,"")+'","fingerflag":' + $("input[name='fingerflag']:checked").val() + ',"fingerbase":"' + fingerbase +  '","rname":"智能锁管理/用户管理/采集指纹"}';
	if(fingeropt == 1){
		//录入指纹
		$.ajax({
			type:"post",
			contentType: "application/json;charset=UTF-8",
			url: "fingeradd.do?",
			async:false,
			data:datastring,
	     	dataType:"json",
	        success: function(msg) {    //数据提交成功时返回数据
	        	//debugger;
	        	layer.msg(msg.desc);						
	        },
	        error : function(e){
	        	if(e.status == 200){
	        		parent.location.href = "login";
	        	}else{
	        		alert(e.status);
	                alert(e.responseText);
	        	}
	        }

		});		
	}else if(fingeropt == 2){
		//验证指纹
		$.ajax({
			type:"post",
			contentType: "application/json;charset=UTF-8",
			url: "fingerauth.do?",
			async:false,
			data:datastring,
	     	dataType:"json",
	        success: function(msg) {    //数据提交成功时返回数据
	        	//debugger;
	        	layer.msg(msg.desc);					
	        },
	        error : function(e){
	        	if(e.status == 200){
	        		parent.location.href = "login";
	        	}else{
	        		alert(e.status);
	                alert(e.responseText);
	        	}
	        }

		});		
	}else if(fingeropt == 3){
		//验证指纹
		$.ajax({
			type:"post",
			contentType: "application/json;charset=UTF-8",
			url: "fingerquery.do?",
			async:false,
			data:datastring,
	     	dataType:"json",
	        success: function(msg) {    //数据提交成功时返回数据
	        	//debugger;
	        	layer.msg(msg.desc);					
	        },
	        error : function(e){
	        	if(e.status == 200){
	        		parent.location.href = "login";
	        	}else{
	        		alert(e.status);
	                alert(e.responseText);
	        	}
	        }

		});		
	}
	
}

function dialog_orgselect(){
	layer.open({
		  type: 2 //0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层） 
		  ,title: "选择机构" //标题
		  ,skin:"layui-layer-lan"   //layui-layer-lan:蓝色，layui-layer-molv：墨绿色，默认灰色
		  ,area: ['350px', '400px'] //宽度、高度
		  ,shade: 0.3
		  ,offset: 'auto'
		  ,anim:5 //弹出动画
		  ,shadeClose: false //弹框出现后，允许点击其它地方关闭
		  ,content: 'getorgtree.html'     //内容
		  ,btn: ['取消'] //只是为了演示		
		  ,success:function (layero,index) {
			  debugger;
              var iframe = window['layui-layer-iframe' + index];              
              iframe.child("locktransfer_org","porg");
      	  }
		  ,yes: function(index, layero){
		    //按钮【按钮一】的回调
			 	 //$("#orgtree").css('display','none'); 
			 	layer.close(index);
		  }
		  ,cancel: function(index,layero){ 
			    //右上角关闭回调
			    //$("#orgtree").css('display','none'); 
		 }
       });
}
</script>
</body>
</html>
